/*
 * @Author: chengsl
 * @Date: 2023-02-10 13:17:35
 * @LastEditors: chengsl
 * @LastEditTime: 2023-02-10 13:52:05
 * @Description: file content
 */
import { encrypt, decrypt } from '@/utils/sm4.js'
// import { key } from '@/settings.js'
const key = strToUtf8Bytes('chengNanHuaYikai')

/**
 * 字符串转成字节
 */
function strToUtf8Bytes(str) {
  const utf8 = []
  for (let ii = 0; ii < str.length; ii++) {
    let charCode = str.charCodeAt(ii)
    if (charCode < 0x80) utf8.push(charCode)
    else if (charCode < 0x800) {
      utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f))
    } else if (charCode < 0xd800 || charCode >= 0xe000) {
      utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f))
    } else {
      ii++
      // Surrogate pair:
      // UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
      // splitting the 20 bits of 0x0-0xFFFFF into two halves
      charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff))
      utf8.push(
        0xf0 | (charCode >> 18),
        0x80 | ((charCode >> 12) & 0x3f),
        0x80 | ((charCode >> 6) & 0x3f),
        0x80 | (charCode & 0x3f),
      )
    }
  }
  // 兼容汉字，ASCII码表最大的值为127，大于127的值为特殊字符
  for (let jj = 0; jj < utf8.length; jj++) {
    var code = utf8[jj]
    if (code > 127) {
      utf8[jj] = code - 256
    }
  }
  return utf8
}
/**
 * AES加密 ：字符串 key  返回base64
 */
export function Encrypt(word) {
  if (!word) return ''
  return encrypt(JSON.stringify(word), key)
}
/**
 * AES 解密 ：字符串 key  返回base64
 *
 */
export function Decrypt(word) {
  const str = decrypt(word, key)
  let dWord = ''
  try {
    dWord = JSON.parse(str)
  } catch (err) {
    dWord = str
  }
  return dWord
}
